//
//  DYRiliChoiceDaysView.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/3/12.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import SwiftDate

/// 日历 - 选择一段时间
class DYRiliChoiceDaysView: DYRiliView {
    
    var wan:Int = 0
    
    override var selectDayDate: Date! {
        didSet {
            showLb.text = "共\(0)晚"
        }
    }
    
    // 选择的结束天
    var selectEndDayDate: Date! {
        didSet {
            if let end = selectEndDayDate {
                wan = end.day - selectDayDate.day
            } else {
                wan = 0
            }
            
            showLb.text = "共\(wan)晚"
        }
    }

    
    override func initViews() {
        super.initViews()
        let endDayDate = Date() + 1.days
        selectEndDayDate = Date("\(endDayDate.year)-\(endDayDate.month)-\(endDayDate.day + 1) \(dayLastTime)")!
    }
    
    override func compAction() {
        if let _ = selectEndDayDate {
//            self.isHidden = true
            self.passParamsClosure?((selectDayDate, selectEndDayDate, wan))
        } else if let v = self.currentVC {
            v.sy_toast("未选择结束日期")
        }
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell: DYRiliCell? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(DYRiliCell.self), for: indexPath) as? DYRiliCell
        
        let date = dates[indexPath.row]
        // 每月1号开始前的空白部分
        var day = ""
        if date.year != 1000 {
            day = "\(date.day)"
        }

        if let start = selectDayDate, let end = selectEndDayDate {
            if start <= date && date <= end {
                cell?.configCell("\(day)", true, date.isInPast)
            } else {
                cell?.configCell("\(day)", false, date.isInPast)
            }
        } else if let start = selectDayDate { // 必有开始时间
            if start == date {
                cell?.configCell("\(day)", true, date.isInPast)
            } else {
                cell?.configCell("\(day)", false, date.isInPast)
            }
        }
        
        
        return cell!
        
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let date = dates[indexPath.row]
        if date.isInPast {
            return
        }
        if let _ = selectDayDate, let _ = selectEndDayDate {
            selectDayDate = date
            selectEndDayDate = nil
        } else if let start = selectDayDate {// 必有开始时间
            if date < start {
                selectDayDate = date
            } else {
                selectEndDayDate = date
            }
        }
        
        self.collectionView.reloadData()
    }

}
